package com.guagua.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guagua.blog.entity.ViewLog;
import com.guagua.blog.mapper.ViewLogMapper;
import com.guagua.blog.service.ViewLogService;
import com.guagua.system.security.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class ViewLogServiceImpl extends ServiceImpl<ViewLogMapper, ViewLog> implements ViewLogService {
    
    @Override
    public void recordView(Long articleId, String ip) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 查询是否有阅读记录
        ViewLog viewLog = getOne(new LambdaQueryWrapper<ViewLog>()
            .eq(ViewLog::getUserId, userId)
            .eq(ViewLog::getArticleId, articleId));
        
        if (viewLog == null) {
            // 第一次阅读，创建新记录
            viewLog = new ViewLog();
            viewLog.setArticleId(articleId);
            viewLog.setUserId(userId);
            viewLog.setIp(ip);
            viewLog.setViewTime(LocalDateTime.now());
            save(viewLog);
        } else {
            // 已读过，更新阅读时间
            viewLog.setViewTime(LocalDateTime.now());
            viewLog.setIp(ip);  // 同时更新IP，记录最后一次访问的IP
            updateById(viewLog);
        }
    }
} 